import { checkMainType } from '@/pages/InventoryAnalysis/components/ApiService';
import type { FowardSearchRenderA } from '@/pages/InventoryAnalysis/components/search/SearchRenderA';
import SearchRenderA from '@/pages/InventoryAnalysis/components/search/SearchRenderA';
import useCustomDataHook from '@/pages/InventoryAnalysis/customer/useCustomDataHook';
import getApiData from '@/services/cpasRequest';
import { useModel } from '@@/exports';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import CpasLayout from '~/public/cpas-business/cpas-table/CpasLayout';
const InventoryAnalysisCustomerYearAnalysis: React.FC = (props: any) => {
  const pageType = props.params?.type;

  const globalModel = useModel('@@initialState') as any;
  const dbname = globalModel?.initialState?.curPart?.dbname;

  const LayoutRef = useRef<any>();

  const ztModel = useModel('ztModel');

  const { ztDates } = ztModel;

  // ----------------------------- 获取默认年度，和组件行为保持一致 , 用于首次请求接口
  // const { qjYearData: defaultYearDate } = qjModel;
  /**
   * 年度
   */
  const [dates, setDates] = useState<string[]>([]);
  /**
   * 排名
   */
  const [ranking, setRanking] = useState<number | null>(10);

  /**
   * 树数据
   */
  const [treeListData, setTreeListData] = useState<any[]>([]);
  /**
   * 主表动态表头数据
   */
  const { tableColumnData } = useCustomDataHook(dates, 'year', false);

  const { tableColumnData: detailTableColumnData } = useCustomDataHook(dates, 'year', true);

  // 表体数据
  const [tableData, setTableData] = useState<any[]>([]);

  // 查询条件
  const SearchRenderARef = useRef<FowardSearchRenderA | null>(null);

  // 当选选中的树节点
  const [selectTreeNode, setSelectTreeNode] = useState<any>(null);

  /**
   * 刷新期间
   */
  useEffect(() => {
    ztModel.refresh();
  }, []);

  useEffect(() => {
    setDates(ztDates);
  }, [ztDates]);

  /**
   * 加载Tree
   */
  useEffect(() => {
    if (dbname) {
      getApiData('get.customer.type', { dbname })
        .then((responseData) => {
          if (responseData.ok) {
            setTreeListData(responseData.data);
            setSelectTreeNode(responseData.data[0]);
          }
        })
        .catch((error) => {
          console.error(error);
        });
    }
  }, [dbname]);

  /**
   * 首次，加载表格数据
   */
  useEffect(() => {
    if (selectTreeNode) {
      // 对比两次日期是否相同;
      refreshTableData(dates, ranking, dbname, selectTreeNode.name);
    }
  }, [dbname, dates, selectTreeNode, ranking]);

  async function refreshTableData(
    datesParam: any[],
    rankingParam: number | null,
    dbnameParam: string,
    typeName: string,
  ) {
    // 检测业务类型是否存在
    const result = await checkMainType(dbnameParam, '销售');
    if (!result) {
      return;
    }

    const endYear = datesParam[datesParam.length - 1];
    const apiParams = {
      name: 'Analysis.Inventory.KHXSND',
      params: {
        dbname: dbnameParam,
        startYear: datesParam[0],
        endYear: endYear,
        dates: datesParam,
        ranking: rankingParam,
        dataFieldA: ['Qty', 'cost'],
        dataFieldB: ['cost'],
        dataFieldC: ['OrderIndex'],
        typeName: typeName === '全部' ? null : typeName,
      },
    };

    getApiData(apiParams.name, { ...apiParams.params })
      .then((responseData) => {
        if (responseData.ok) {
          // const sortData = customSortZeroData(`${endYear}_OrderIndex`, responseData.data, 'asc');
          setTableData(responseData.data);
        }
      })
      .catch((error) => {
        console.error(error);
      });
  }

  function renderSearch() {
    return (
      <SearchRenderA
        yearDate={null}
        ref={SearchRenderARef}
        ranking={ranking}
        dbname={dbname}
        setUserTypeCallback={refreshCallBack}
      />
    );
  }

  async function searchCallback() {
    const searchValues = SearchRenderARef.current?.getFormSearchValues() || null;
    if (!searchValues) {
      return;
    }
    const {
      dates: datesSearchParam,
      startYear,
      endYear,
      ranking: rankingSearchParam,
    } = searchValues;
    setDates(datesSearchParam as string[]);
    setRanking(rankingSearchParam);
  }

  async function refreshCallBack() {
    await searchCallback();
  }

  function treeChange(e: any) {
    setSelectTreeNode({ ...e.node.itemData });
  }

  const devToolLeftbar = useMemo(() => {
    return [
      {
        widget: 'dxButton',
        options: {
          text: '查看全部明细',
          type: 'default',
          onClick: () => {
            console.log('查看明细', SearchRenderARef.current?.getFormSearchValues());
            if (LayoutRef.current) {
              LayoutRef.current.addTab('查看全部明细');
            }
          },
        },
      },
    ];
  }, []);

  /**
   * 穿透使用-双击加载单条的devGrid数据
   */
  const loadSingleDevGridData = useCallback(
    async (rowData: any) => {
      // 穿透到客户商品明细
      const apiParams = {
        name: 'Analysis.Inventory.KHXSSPND',
        params: {
          dbname: dbname,
          startYear: dates[0],
          endYear: dates[dates.length - 1],
          dates: dates,
          ranking: null,
          dataFieldA: ['Qty', 'cost'],
          dataFieldB: [
            {
              Qty: {
                field: 'Qty',
              },
              cost: {
                field: 'cost',
              },
            },
          ],
          dataFieldC: ['OrderIndex'],
          custID: rowData.custID,
        },
      };

      try {
        const respose = await getApiData(apiParams.name, { ...apiParams.params });
        return {
          dataSource: respose.data,
        };
      } catch (e) {
        return {
          dataSource: [],
        };
      }
    },
    [dates, dbname],
  );

  /**
   * 穿透-全部明细
   */
  const loadAllDevGridData = useCallback(async () => {
    // 穿透到客户商品明细
    const apiParams = {
      name: 'Analysis.Inventory.KHXSSPND',
      params: {
        dbname: dbname,
        startYear: dates[0],
        endYear: dates[dates.length - 1],
        dates: dates,
        ranking: null,
        dataFieldA: ['Qty', 'cost'],
        dataFieldB: [
          {
            Qty: {
              field: 'Qty',
            },
            cost: {
              field: 'cost',
            },
          },
        ],
        dataFieldC: ['OrderIndex'],
      },
    };

    try {
      const respose = await getApiData(apiParams.name, { ...apiParams.params });
      return {
        dataSource: respose.data,
      };
    } catch (e) {
      return {
        dataSource: [],
      };
    }
  }, [dates, dbname]);

  /**
   * 获取查询表单数据
   */
  const getSearchFormValue = useCallback(() => {
    const searchValues = SearchRenderARef.current?.getFormSearchValues() || null;
    if (!searchValues) {
      return {};
    }
    return {
      ...searchValues,
    };
  }, []);

  return (
    <>
      <div
        style={{
          border: '0px solid green',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        {/*{treeListData?.length > 0 ? (*/}
        <CpasLayout
          ref={LayoutRef}
          pageType={pageType}
          treeListData={treeListData}
          isLeftTree={true}
          tableColumnsData={tableColumnData}
          tableData={tableData}
          refreshBtnCallback={refreshCallBack}
          renderSearch={renderSearch}
          treeClickCallback={treeChange}
          searchClickCallback={searchCallback}
          devToolLeftItem={devToolLeftbar}
          getSearchFormData={getSearchFormValue}
          parentRef={LayoutRef}
          searchElement={SearchRenderA}
          detailKey={'custName'}
          detailTableColumnData={detailTableColumnData} // TODO 穿透表的列
          loadAllDevGridData={loadAllDevGridData}
          loadSingleDevGridData={loadSingleDevGridData}
        />
        {/*) : null}*/}
      </div>
    </>
  );
};

export default InventoryAnalysisCustomerYearAnalysis;
